package byx.container.core;

import byx.container.core.exception.IdDuplicatedException;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class SimpleContainer implements ObjectRegistry, Container {
    private final Map<String, RegisterInfo> registerInfoMap = new ConcurrentHashMap<>();

    @Override
    public void register(RegisterInfo registerInfo) {
        String id = registerInfo.getId();
        if (registerInfoMap.containsKey(id)) {
            throw new IdDuplicatedException(id);
        }
        registerInfoMap.put(id, registerInfo);
    }

    @Override
    public void unregister(Predicate<RegisterInfo> predicate) {
        registerInfoMap.values().removeIf(predicate);
    }

    @Override
    public List<RegisterInfo> getRegisterInfos(Predicate<RegisterInfo> predicate) {
        return registerInfoMap.values().stream()
                .filter(predicate)
                .sorted(Comparator.comparingInt(RegisterInfo::getOrder))
                .collect(Collectors.toList());
    }
}
